import React, { PureComponent } from 'react';
import { Modal, Form, Input, Row, Select } from 'antd';
import lodash from 'lodash';
import { CompareRuleArray } from '../../../utils/enum';
// import classNames from 'classnames';
import styles from './ExpectValuesModalEditor.less';

@Form.create()
export default class ExpectValuesModalEditor extends PureComponent {

  // 重置组件
  reset = () => {
    const { form } = this.props;
    form.resetFields();
    form.setFieldsValue({ compareRule: undefined });
  }

  init = ({ compareRule }) => {
    const { form } = this.props;
    form.setFieldsValue({ compareRule });
  }

  // 保存
  onCreate = () => {
    const { form, onOk, expectValueData: { metricTitle } } = this.props;
    if (!(onOk instanceof Function)) return;
    form.validateFields((err, formValues) => {
      if (err) return;
      const { title, key, compareRule, value } = formValues;
      const showValueInput = lodash.findIndex(['exists', 'not_exists'], item => item === compareRule) === -1;
      if (showValueInput) {
        onOk({ metricTitle, title, key, compareRule, value });
      } else {
        onOk({ metricTitle, title, key, compareRule });
      }
    });
  }

  render() {
    const { expectValueData, addFlag, titleExists, resetFunc, initFunc, visible, confirmLoading, onCancel, form } = this.props;
    const { getFieldDecorator, getFieldValue } = form;
    if (resetFunc instanceof Function) resetFunc(this.reset);
    if (initFunc instanceof Function) initFunc(this.init);
    const width = 450;
    const compareRule = getFieldValue('compareRule') || expectValueData.compareRule;
    const showValueInput = lodash.findIndex(['exists', 'not_exists'], item => item === compareRule) === -1;
    return (
      <Modal
        width={600}
        visible={visible}
        confirmLoading={confirmLoading}
        title={`${addFlag ? '新增' : '编辑'}预期响应结果`}
        okText={addFlag ? '新增' : '保存'}
        onCancel={onCancel}
        onOk={this.onCreate}
        maskClosable={false}
        bodyStyle={{ padding: '24px 24px 12px 24px' }}
      >
        <Form layout="inline" className={styles.form}>
          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="标题">
              {getFieldDecorator('title', {
                initialValue: expectValueData ? expectValueData.title : undefined,
                validateFirst: true,
                rules: [
                  { required: true, whitespace: true, min: 3, max: 32, message: '标题长度必须是3~32字符' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (addFlag && value && lodash.trim(value) !== '') {
                        if (titleExists instanceof Function) {
                          if (titleExists(expectValueData.metricTitle, value)) {
                            errors.push("标题不能重复");
                          }
                        }
                      }
                      callback(errors);
                    },
                  },
                ],
              })(
                <Input placeholder="预期响应结果标题" style={{ width }} disabled={!addFlag} />
              )}
            </Form.Item>
          </Row>
          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="结果Key">
              {getFieldDecorator('key', {
                initialValue: expectValueData ? expectValueData.key : undefined,
                validateFirst: true,
                rules: [
                  { required: true, whitespace: true, min: 1, max: 512, message: '结果Key长度必须是1~512字符' },
                ],
              })(
                <Input placeholder="结果Key，如：hits.hits[0]._source.jdbcPoolingCount" style={{ width }} />
              )}
            </Form.Item>
          </Row>
          <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
            <Form.Item label="比较规则">
              {getFieldDecorator('compareRule', {
                initialValue: expectValueData ? expectValueData.compareRule : undefined,
                validateFirst: true,
                rules: [
                  { required: true, whitespace: true, message: '比较规则必填' },
                ],
              })(
                <Select style={{ width }}>
                  {CompareRuleArray.map(item => (<Select.Option key={item.value} value={item.value}>{`${item.label}(${item.description})`}</Select.Option>))}
                </Select>
              )}
            </Form.Item>
          </Row>
          {showValueInput ? (
            <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
              <Form.Item label="预期结果">
                {getFieldDecorator('value', {
                  initialValue: expectValueData ? expectValueData.value : undefined,
                  validateFirst: true,
                  rules: [
                    { required: false, whitespace: false, message: '预期结果值不能为空' },
                  ],
                })(
                  <Input.TextArea placeholder="预期结果值" rows={2} autosize={{ minRows: 2, maxRows: 8 }} style={{ width, maxWidth: 1000 }} />
                )}
              </Form.Item>
            </Row>
          ) : ''}
        </Form>
      </Modal>
    );
  }
}
